<template>
  <el-form ref="pwdForm"
           :model="pwdData"
           :rules="rules"
           :inline="true">
    <el-form-item label="旧密码"
                  label-width="100px"
                  prop="oldPassword"
                  style="width:100%">
      <el-input v-model="pwdData.oldPassword"
                name="oldPassword"
                type="password" />
    </el-form-item>
    <el-form-item label="新密码"
                  label-width="100px"
                  prop="newPassword"
                  style="width:100%">
      <el-input v-model="pwdData.newPassword"
                type="password" />
    </el-form-item>
    <el-form-item label="确认新密码"
                  label-width="100px"
                  prop="confirmPassword">
      <el-input v-model="pwdData.confirmPassword"
                type="password" />
    </el-form-item>
    <el-form-item>
      <el-button :loading="loading"
                 type="primary"
                 @click="submit">修改密码</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { updateMyPassword } from '@/api/admin'

export default {
  data() {
    const validConfirmPassword = (rule, value, callback) => {
      if (this.pwdData.newPassword && value !== this.pwdData.newPassword) {
        callback(new Error('您两次输入的新密码不一致'))
      } callback()
    }
    return {
      pwdData: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
        newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
        confirmPassword: [{ required: true, trigger: 'blur', validator: validConfirmPassword }]
      },
      loading: false
    }
  },
  methods: {
    submit() {
      this.$refs.pwdForm.validate((valid) => {
        if (valid) {
          this.loading = true
          updateMyPassword(this.pwdData).then(res => {
            this.$message({
              message: '密码修改成功',
              type: 'success',
              duration: 3 * 1000
            })
            this.handleFormReset()
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    handleFormReset() {
      this.$refs.pwdForm.resetFields()
    }
  }
}
</script>
